import uuid
from flask import Blueprint, request, jsonify
from services.chroma_service import ChromaService

vector_bp = Blueprint('vector', __name__)
chroma_service = ChromaService()

#######################################
# API：Collection 的增删改查
#######################################

# 查询所有 collections
@vector_bp.route('/', methods=['GET'])
def list_collections():
    # 获取分页和搜索参数
    page = int(request.args.get("page", 1))
    page_size = int(request.args.get("page_size", 10))
    search = request.args.get("search", "").lower()
    
    try:
        result = chroma_service.list_collections(page, page_size, search)
        return jsonify(result)
    except Exception as e:
        return jsonify({"error": str(e)}), 500

# 新建 collection
@vector_bp.route('/', methods=['POST'])
def create_collection():
    data = request.get_json()
    name = data.get('name')
    if not name:
        return jsonify({"error": "Collection name is required"}), 400
    try:
        result = chroma_service.create_collection(name)
        return jsonify(result)
    except Exception as e:
        return jsonify({"error": str(e)}), 500
    
# 修改 collection（例如重命名操作：复制数据到新集合然后删除旧集合）
@vector_bp.route('/<collection_name>', methods=['PUT'])
def update_collection(collection_name):
    data = request.get_json()
    new_name = data.get('new_name')
    if not new_name:
        return jsonify({"error": "New collection name is required"}), 400
    try:
        result = chroma_service.update_collection(collection_name, new_name)
        return jsonify(result)
    except Exception as e:
        return jsonify({"error": str(e)}), 500

# 删除 collection
@vector_bp.route('/<collection_name>', methods=['DELETE'])
def delete_collection(collection_name):
    try:
        result = chroma_service.delete_collection(collection_name)
        return jsonify(result)
    except Exception as e:
        return jsonify({"error": str(e)}), 500
    
#######################################
# API：记录的增删改查与检索（在具体 collection 下）
#######################################

# 分页查询记录，支持简单的“搜索”（在 document 字段中模糊匹配）
@vector_bp.route('/<collection_name>/records', methods=['GET'])
def list_records(collection_name):
    # 获取分页参数
    page = int(request.args.get("page", 1))
    page_size = int(request.args.get("page_size", 10))
    
    # 获取查询参数
    search_type = request.args.get("search_type")
    record_id = request.args.get("id")
    query_text = request.args.get("query_text")
    metadata_filter = request.args.get("metadata_filter")
    document_filter = request.args.get("document_filter")
    n_results_requested = int(request.args.get("n_results", 1000))
    
    try:
        result = chroma_service.list_records(collection_name, page, page_size, search_type, record_id, query_text, metadata_filter, document_filter, n_results_requested)
        return jsonify(result)
    except Exception as e:
        print(f"Error in list_records: {str(e)}")  # 添加错误日志
        return jsonify({"error": str(e)}), 500

# 新建记录
@vector_bp.route('/<collection_name>/records', methods=['POST'])
def create_record(collection_name):
    data = request.get_json()
    record_id = data.get("id", str(uuid.uuid4()))
    document = data.get("document", "")
    # 如果 metadata 不存在或为空，则不包含在参数中
    metadata = data.get("metadata")
    
    if not document:
        return jsonify({"error": "Document content is required"}), 400
        
    try:
        result = chroma_service.create_record(collection_name, record_id, document, metadata)
        return jsonify(result)
    except Exception as e:
        return jsonify({"error": str(e)}), 500


# 更新记录（模拟：先删除再添加）
@vector_bp.route('/<collection_name>/records/<record_id>', methods=['PUT'])
def update_record(collection_name, record_id):
    data = request.get_json()
    document = data.get("document", "")
    # 如果 metadata 不存在或为空，则不包含在参数中
    metadata = data.get("metadata")
    
    if not document:
        return jsonify({"error": "Document content is required"}), 400
        
    try:
        result = chroma_service.update_record(collection_name, record_id, document, metadata)
        return jsonify(result)
    except Exception as e:
        return jsonify({"error": str(e)}), 500

# 删除单个记录
@vector_bp.route('/<collection_name>/records/<record_id>', methods=['DELETE'])
def delete_record(collection_name, record_id):
    try:
        result = chroma_service.delete_record(collection_name, record_id)
        return jsonify(result)
    except Exception as e:
        return jsonify({"error": str(e)}), 500
    
# 批量删除记录，传入 JSON 格式的 { "ids": [id1, id2, ...] }
@vector_bp.route('/<collection_name>/records', methods=['DELETE'])
def batch_delete_records(collection_name):
    data = request.get_json()
    ids = data.get("ids")
    if not ids or not isinstance(ids, list):
        return jsonify({"error": "List of record ids is required"}), 400
    try:
        result = chroma_service.batch_delete_records(collection_name, ids)
        return jsonify(result)
    except Exception as e:
        return jsonify({"error": str(e)}), 500